//
//  BZYHomeController.m
//  BZYMeituan
//
//  Created by 毕仲阳 on 16/9/15.
//  Copyright © 2016年 mycompany. All rights reserved.
//

#import "BZYHomeController.h"
#import "BZYHomeNavView.h"
#import "BZYCategoryController.h"
#import "BZYDistrictController.h"
#import "BZYCityModel.h"
#import "BZYSortController.h"
#import "BZYSortModel.h"
#import "BZYCategoryModel.h"
#import "BZYDistrictModel.h"

#import "AwesomeMenu.h"
#import "BZYDealCell.h"

#import "DPAPI.h"
@interface BZYHomeController ()<AwesomeMenuDelegate,DPRequestDelegate>

@property (nonatomic,copy) NSString *selectedCityName;
@property (nonatomic, copy) NSString *selectCategoryName;
@property (nonatomic, copy) NSString *selectDistrctName;
//@property (nonatomic, copy) NSString *selectSortName;
@property (nonatomic, strong) NSNumber *selectSortValue;


@property (nonatomic,weak) BZYHomeNavView *categoryNavView;
@property (nonatomic,weak) BZYHomeNavView *districtNavView;
@property (nonatomic,weak) BZYHomeNavView *sortNavView;
//当前页面
@property (nonatomic,assign) NSInteger currentPage;
@end

@implementation BZYHomeController

static NSString * const reuseIdentifier = @"dealCell";
- (instancetype)init
{
    //self = [super initWithCollectionViewLayout:[[UICollectionViewFlowLayout alloc]init]];
    self = [super init];
    if (self) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake(BZYDealCellWidth, BZYDealCellWidth);
        
        self = [self initWithCollectionViewLayout:layout];
    }
    return self;
}
//旋转屏幕会调用
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    NSInteger col = size.width > size.height ? 3 : 2;
    CGFloat inset = (size.width - col * BZYDealCellWidth)/(col + 1);
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionViewLayout;
    layout.sectionInset = UIEdgeInsetsMake(inset, inset, inset, inset);
    layout.minimumLineSpacing = inset;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self viewWillTransitionToSize:[UIScreen mainScreen].bounds.size withTransitionCoordinator:self.transitionCoordinator];
    
    self.collectionView.backgroundColor = BZYColor(230, 230, 230);
    //[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    [self.collectionView registerNib:[UINib nibWithNibName:@"BZYDealCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    // Do any additional setup after loading the view.
    [self setLeftNav];
    [self setRightNav];
    //添加分类通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(categoryDidChangeNotification:) name:BZYCategoryDidChangeNotification object:nil];
    //添加选择城市的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cityDidChangeNotification:) name:BZYCityDidChangeNotification object:nil];
    //添加选择区域的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(districtDidChangeNotification:) name:BZYDistrictDidChangeNotification object:nil];
    //添加排序选择通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sortDidChangeNotification:) name:BZYSortDidChangeNotification object:nil];
    [self setAwesomeMenu];
}

#pragma mark - 添加AwesomeMenu按钮
- (void)setAwesomeMenu
{
    //1. 中间的startItem
    AwesomeMenuItem *startItem = [[AwesomeMenuItem alloc]
                                  initWithImage:[UIImage imageNamed:@"icon_pathMenu_background_normal"]
                                  highlightedImage:[UIImage imageNamed:@"icon_pathMenu_background_highlighted"]
                                  ContentImage:[UIImage imageNamed:@"icon_pathMenu_mainMine_normal"]
                                  highlightedContentImage:nil];
    
    //2. 添加其他几个按钮
    AwesomeMenuItem *item0 = [[AwesomeMenuItem alloc]
                              initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"]
                              highlightedImage:nil
                              ContentImage:[UIImage imageNamed:@"icon_pathMenu_mainMine_normal"]
                              highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_mainMine_highlighted"]];
    
    AwesomeMenuItem *item1 = [[AwesomeMenuItem alloc]
                              initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"]
                              highlightedImage:nil
                              ContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_normal"]
                              highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_highlighted"]];
    AwesomeMenuItem *item2 = [[AwesomeMenuItem alloc]
                              initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"]
                              highlightedImage:nil
                              ContentImage:[UIImage imageNamed:@"icon_pathMenu_scan_normal"]
                              highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_scan_highlighted"]];
    
    AwesomeMenuItem *item3 = [[AwesomeMenuItem alloc]
                              initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"]
                              highlightedImage:nil
                              ContentImage:[UIImage imageNamed:@"icon_pathMenu_more_normal"]
                              highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_more_highlighted"]];
    
    NSArray *items = @[item0, item1, item2, item3];
    AwesomeMenu *menu = [[AwesomeMenu alloc]initWithFrame:CGRectZero startItem:startItem menuItems:items];
    [self.view addSubview:menu];
    menu.rotateAddButton = false;
    menu.menuWholeAngle = M_PI_2;
    menu.startPoint = CGPointMake(0, 0);
    [menu mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(100);
        make.bottom.equalTo(self.view).offset(-100);
    }];
    menu.delegate = self;
    menu.alpha = 0.5;
    
}
#pragma mark -AwesomeMenu代理方法
- (void)awesomeMenu:(AwesomeMenu *)menu didSelectIndex:(NSInteger)idx
{
    switch (idx) {
        case 0:
            NSLog(@"1");
            break;
        case 1:
            NSLog(@"2");
            break;
        case 2:
            NSLog(@"3");
            break;
        case 3:
            NSLog(@"4");
            break;
            
        default:
            break;
    }
}

#pragma mark AwesomeMenu将要打开
- (void)awesomeMenuWillAnimateOpen:(AwesomeMenu *)menu
{
    //1. 切换图像
    menu.contentImage = [UIImage imageNamed:@"icon_pathMenu_cross_normal"];
    
    //2. 更改透明度
    [UIView animateWithDuration:.25 animations:^{
        menu.alpha = 1;
    }];
}
#pragma mark AwesomeMenu将要关闭
- (void)awesomeMenuWillAnimateClose:(AwesomeMenu *)menu
{
    //1. 切换图像
    menu.contentImage = [UIImage imageNamed:@"icon_pathMenu_mainMine_normal"];
    
    //2. 更改透明度
    [UIView animateWithDuration:.25 animations:^{
        menu.alpha = 0.5;
    }];
}

#pragma mark -网络请求
- (void)loadNewDeals
{
    DPAPI *api = [[DPAPI alloc]init];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    self.currentPage = 1;
    params[@"city"] = @"北京";
    params[@"category"] = self.selectCategoryName;
    //区域
    params[@"region"] = self.selectDistrctName;
    
    // 排序
    params[@"sort"] = self.selectSortValue;

    params[@"page"] = @(self.currentPage);
    
    params[@"limit"] = @2;
    [api requestWithURL:@"v1/deal/find_deals" params:params delegate:self];
}

- (void)request:(DPRequest *)request didFinishLoadingWithResult:(id)result
{
    NSLog(@"result = %@",result);
}
- (void)request:(DPRequest *)request didFailWithError:(NSError *)error
{
    NSLog(@"error = %@",error);
}
#pragma mark -通知的方法

#pragma mark 分类的通知
- (void)categoryDidChangeNotification:(NSNotification *)notification
{
    BZYCategoryModel *categoryModel = notification.userInfo[BZYCategoryModelKey];
    NSString *subTitle = notification.userInfo[BZYCategorySubtitleKey];
//    NSLog(@"%@",categoryModel.name);
//    NSLog(@"%@",subTitle);
    [self.categoryNavView setTitle:categoryModel.name];
    [self.categoryNavView setSubtitle:subTitle];
    [self.categoryNavView setIcon:categoryModel.icon highlightIcon:categoryModel.highlighted_icon];
    //
    if ([categoryModel.name isEqualToString:@"全部分类"]) {
        self.selectCategoryName = nil;
    }else if (categoryModel.subcategories.count == 0 || [subTitle isEqualToString:@"全部"]){
        self.selectCategoryName = categoryModel.name;
    }else
    {
        self.selectCategoryName = subTitle;
    }
    [self loadNewDeals];
    [self dismissViewControllerAnimated:true completion:nil];
    
}
#pragma mark 城市选择的通知
- (void)cityDidChangeNotification:(NSNotification *)notification
{
    //NSString *cityName = notification.userInfo[BZYCityNameKey];
    //NSLog(@"%@",cityName);
    self.selectedCityName = notification.userInfo[BZYCityNameKey];
    
    [self.districtNavView setTitle:[NSString stringWithFormat:@"%@-全部",self.selectedCityName]];
    [self.districtNavView setSubtitle:@""];
    //
    [self loadNewDeals];
    [self dismissViewControllerAnimated:true completion:nil];
}
#pragma mark 区域选择的通知
- (void)districtDidChangeNotification:(NSNotification *)notification
{
    BZYDistrictModel *districtModel = notification.userInfo[BZYDistrictModelKey];
    NSString *subtitle = notification.userInfo[BZYDistrictSubtitleKey];
//    NSLog(@"categroyModel: %@", districtModel.name);
//    NSLog(@"subtitle: %@", subtitle);
    [self.districtNavView setTitle:[NSString stringWithFormat:@"%@-%@",self.selectedCityName,districtModel.name]];
    [self.districtNavView setSubtitle:subtitle];
    if ([districtModel.name isEqualToString:@"全部"]) {
        self.selectDistrctName = nil;
    } else if (districtModel.subdistricts.count == 0 || [subtitle isEqualToString:@"全部"]) {
        self.selectDistrctName = districtModel.name;
    } else {
        self.selectDistrctName = subtitle;
    }

    //
    [self loadNewDeals];
    [self dismissViewControllerAnimated:YES completion:nil];

}
#pragma mark 排序选择通知
- (void)sortDidChangeNotification:(NSNotification *)notification
{
    BZYSortModel *model = notification.userInfo[BZYSortModelKey];
    //NSLog(@"%@",model.label);
    [self.sortNavView setSubtitle:model.label];
    self.selectSortValue = model.value;

    //
    [self loadNewDeals];
    [self dismissViewControllerAnimated:true completion:nil];
}

#pragma mark -取消观察者
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
//MARK: -设置左侧的 barButtonItem
- (void)setLeftNav
{
    //1. logo
    UIBarButtonItem *logoItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"icon_meituan_logo"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:nil action:nil];
    logoItem.enabled = false;
    
    //2.分类
    BZYHomeNavView *categoryNavView = [BZYHomeNavView homeNavView];
    UIBarButtonItem *categoryItem = [[UIBarButtonItem alloc]initWithCustomView:categoryNavView];
    
    [categoryNavView addTarget:self action:@selector(categoryClick) forControlEvents:UIControlEventTouchUpInside];
    [categoryNavView setTitle:@"全部"];
    [categoryNavView setSubtitle:@""];
    [categoryNavView setIcon:@"icon_category_-1"  highlightIcon:@"icon_category_highlighted_-1"];
    self.categoryNavView = categoryNavView;
    
    //3.区域
    BZYHomeNavView *districtNavView = [BZYHomeNavView homeNavView];
    UIBarButtonItem *districtNavItem = [[UIBarButtonItem alloc]initWithCustomView:districtNavView];
    [districtNavView setTarget:self action:@selector(districtClick)];
    [districtNavView setTitle:@"北京-全部"];
    [districtNavView setSubtitle:@""];
    self.districtNavView = districtNavView;

    //4.排序
    BZYHomeNavView *sortNavView = [BZYHomeNavView homeNavView];
    UIBarButtonItem *sortItem = [[UIBarButtonItem alloc] initWithCustomView:sortNavView];
    //添加点击事件
    [sortNavView setTarget:self action:@selector(sortClick)];
    
    [sortNavView setTitle:@"排序"];
    [sortNavView setSubtitle:@"默认排序"];
    [sortNavView setIcon:@"icon_sort" highlightIcon:@"icon_sort_highlighted"];
    self.sortNavView = sortNavView;

    self.navigationItem.leftBarButtonItems = @[logoItem,categoryItem,districtNavItem,sortItem];
}
#pragma mark -监听按钮点击事件

- (void)districtClick
{
    BZYDistrictController *vc = [BZYDistrictController new];
    self.selectedCityName = self.selectedCityName == nil? @"北京" : self.selectedCityName;

    //解析城市列表数据
    NSArray *cityList = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"cities.plist" ofType:nil]];
    NSArray *citiesArray = [NSArray yy_modelArrayWithClass:[BZYCityModel class] json:cityList];
    for (BZYCityModel *cityModel in citiesArray) {
        if ([self.selectedCityName isEqualToString:cityModel.name ]) {
            vc.districtArray = cityModel.districts;
        }
    }
    
    vc.modalPresentationStyle = UIModalPresentationPopover;
    UIPopoverPresentationController *popover = vc.popoverPresentationController;
    popover.barButtonItem = self.navigationItem.leftBarButtonItems[2];
    
    [self presentViewController:vc animated:true completion:nil];
}
- (void)categoryClick
{
    //NSLog(@"categoryClick");
    BZYCategoryController *categoryVC = [[BZYCategoryController alloc]init];
    
    categoryVC.modalPresentationStyle = UIModalPresentationPopover;
    UIPopoverPresentationController *popoverVc = categoryVC.popoverPresentationController;
    popoverVc.barButtonItem = self.navigationItem.leftBarButtonItems[1];
    [self presentViewController:categoryVC animated:true completion:nil];
    
}

- (void)sortClick
{
    BZYSortController *sortController = [[BZYSortController alloc]init];
    
    sortController.modalPresentationStyle = UIModalPresentationPopover;
    sortController.popoverPresentationController.barButtonItem = self.navigationItem.leftBarButtonItems[3];
    [self presentViewController:sortController animated:true completion:nil];
}
//MARK: -设置侧右侧的 barButtonItem
- (void)setRightNav
{
    //地图
    UIBarButtonItem *mapItem = [UIBarButtonItem barBuutonItemWithTarget:self action:@selector(mapItemClick) icon:@"icon_map" highlighticon:@"icon_map_highlighted"];
    mapItem.customView.width = 60;
    
    //搜索
    UIBarButtonItem *searchItem = [UIBarButtonItem barBuutonItemWithTarget:self action:@selector(searchItemClick) icon:@"icon_search" highlighticon:@"icon_search_highlighted"];
    searchItem.customView.width = 60;
    self.navigationItem.rightBarButtonItems = @[mapItem,searchItem];
}

- (void)mapItemClick
{
    NSLog(@"mapItemClick");
}
- (void)searchItemClick
{
    NSLog(@"searchItemClick");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark <UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 10;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BZYDealCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    // Configure the cell
    
    return cell;
}

#pragma mark <UICollectionViewDelegate>

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/

@end
